package com.bonc.ioc.base.controller;


import com.bonc.ioc.base.page.PageData;
import com.bonc.ioc.base.page.PageResult;
import com.bonc.ioc.common.util.JsonToolsUtil;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * @author ：liyy
 * @date ：Created in 2020/3/24 17:25
 * @description：
 * @modified By：
 * @version: V1.0
 */
public abstract class BaseController {

	protected String id;
	protected String ids;
	protected HttpServletRequest request;
	protected HttpServletResponse response;
	protected HttpSession session;
	protected PageResult pageResult;

	@ModelAttribute
	public void setReqAndRes(HttpServletRequest request, HttpServletResponse response){
		this.request = request;
		this.response = response;
		this.session = request.getSession();
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}


	/**
	 * 得到PageData
	 */
	public PageData getPageData() {
		return new PageData(request);
	}

	/**
	 * 得到ModelAndView
	 */
	public ModelAndView getModelAndView() {
		return new ModelAndView();
	}
	


	/**
	 * 获取登录用户的IP
	 * 
	 * @throws Exception
	 */
	public String getremoteip() throws Exception {
		String ip = "";
		String headKey="x-forwarded-for";
		if (request.getHeader(headKey) == null) {
			ip = request.getRemoteAddr();
		} else {
			ip = request.getHeader(headKey);
		}
		return ip;
	}


	/**
	 * 客户端返回JSON字符串
	 * @param response
	 * @param object
	 * @return
	 */
	protected String renderString(HttpServletResponse response, Object object) {
		return renderString(response, JsonToolsUtil.toJsonString(object), "application/json");
	}

	/**
	 * 客户端返回字符串
	 * @param response
	 * @param string
	 * @return
	 */
	protected String renderString(HttpServletResponse response, String string, String type) {
		try {
			response.reset();
			response.setContentType(type);
			response.setCharacterEncoding("utf-8");
			response.getWriter().print(string);
			return null;
		} catch (IOException e) {
			return null;
		}
	}
}